package com.itfetter.controller;

import lombok.RequiredArgsConstructor;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.MessageConst;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequiredArgsConstructor
public class RocketmqProducer {
    private final RocketMQTemplate rocketMQTemplate;

    @GetMapping("/rocketmq/synsend")
    public String send(String msg) {
        rocketMQTemplate.syncSend("hello-rocketmq", msg);
        return "消息发送成功";
    }

    @GetMapping("/rocketmq/asynsend")
    public String asynSend(String msg) {
        rocketMQTemplate.asyncSend("hello-rocketmq", msg, new SendCallback() {
            @Override
            public void onSuccess(SendResult sendResult) {
                System.out.println("发送成功" + sendResult.getMsgId());
            }

            @Override
            public void onException(Throwable throwable) {
                System.out.println("发送成功");
                throwable.printStackTrace();
            }
        });
        return "消息发送成功";
    }

    @GetMapping("/rocketmq/onewaysend")
    public String delaySend(String msg) {
        Message message = MessageBuilder.withPayload("msg").build();
        rocketMQTemplate.syncSend("hello-rocketmq", message,1000,2);
        return "消息发送成功";
    }

    @GetMapping("/rocketmq/synsend")
    public String Tagsend(String msg,String tag) {
        rocketMQTemplate.syncSend("hello-rocketmq:"+tag, msg);
        return "消息发送成功";
    }
    @GetMapping("/rocketmq/onewaysend")
    public String keySend(String msg) {
        Message message = MessageBuilder.withPayload(msg).setHeader(MessageConst.PROPERTY_KEYS,"12321").build();
        rocketMQTemplate.syncSend("hello-rocketmq", message,1000,2);
        return "消息发送成功";
    }
    @GetMapping("/rocketmq/onewaysend")
    public String propertiseSend(String msg) {
        Map<String,Object>map=new HashMap<>();
        map.put("name","xiaohei");
        map.put("age",17);
        rocketMQTemplate.convertAndSend("hello-rocketmq",msg,map);
        return "消息发送成功";
    }
}
